import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ShoppingFrame extends JFrame {

    private Map<String, Integer> inventory = new HashMap<>(); // 商品库存
    private Map<String, Integer> cart = new HashMap<>(); // 购物车
    private ArrayList<String> purchaseHistory = new ArrayList<>(); // 购物历史
    private JTextArea cartArea;
    private JTextArea historyArea;
    private JTextArea inventoryArea; // 库存信息显示区域

    public ShoppingFrame() {
        setTitle("购物");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new BorderLayout());
        add(panel);

        // 初始化商品库存
        inventory.put("1001", 50);
        inventory.put("1002", 30);
        inventory.put("1003", 20);
        inventory.put("1004", 15);
        inventory.put("1005", 10);
        inventory.put("1006", 12);
        inventory.put("1007", 42);
        inventory.put("2008", 36);
        inventory.put("2023", 24);
        inventory.put("2046", 18);

        // 创建和配置UI组件
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);

        JLabel itemLabel = new JLabel("商品编号:");
        gbc.gridx = 0;
        gbc.gridy = 0;
        inputPanel.add(itemLabel, gbc);

        JTextField itemField = new JTextField(10);
        gbc.gridx = 1;
        gbc.gridy = 0;
        inputPanel.add(itemField, gbc);

        JLabel quantityLabel = new JLabel("数量:");
        gbc.gridx = 0;
        gbc.gridy = 1;
        inputPanel.add(quantityLabel, gbc);

        JTextField quantityField = new JTextField(10);
        gbc.gridx = 1;
        gbc.gridy = 1;
        inputPanel.add(quantityField, gbc);

        JButton addButton = new JButton("加入购物车");
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        inputPanel.add(addButton, gbc);

        JButton removeButton = new JButton("从购物车中移除");
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 1;
        inputPanel.add(removeButton, gbc);

        JButton modifyButton = new JButton("修改购物车中的商品");
        gbc.gridx = 1;
        gbc.gridy = 3;
        inputPanel.add(modifyButton, gbc);

        JButton checkoutButton = new JButton("结账");
        gbc.gridx = 0;
        gbc.gridy = 4;
        inputPanel.add(checkoutButton, gbc);

        JButton historyButton = new JButton("查看购物历史");
        gbc.gridx = 1;
        gbc.gridy = 4;
        inputPanel.add(historyButton, gbc);

        JButton backButton = new JButton("返回客户菜单");
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 2;
        inputPanel.add(backButton, gbc);

        panel.add(inputPanel, BorderLayout.CENTER);

        // 库存信息显示区域
        inventoryArea = new JTextArea(10, 30);
        inventoryArea.setEditable(false);
        JScrollPane inventoryScrollPane = new JScrollPane(inventoryArea);


        cartArea = new JTextArea(10, 30);
        cartArea.setEditable(false);
        JScrollPane cartScrollPane = new JScrollPane(cartArea);

        historyArea = new JTextArea(10, 30);
        historyArea.setEditable(false);
        JScrollPane historyScrollPane = new JScrollPane(historyArea);

        JPanel infoPanel = new JPanel(new GridLayout(1, 3));
        infoPanel.add(inventoryScrollPane);
        infoPanel.add(cartScrollPane);
        infoPanel.add(historyScrollPane);

        add(inputPanel, BorderLayout.NORTH);
        add(infoPanel, BorderLayout.CENTER);
        // 添加按钮事件处理
        backButton.addActionListener(e -> {
            dispose();  // 关闭当前窗口
            CustomerMenuFrame customerMenuFrame = new CustomerMenuFrame();  // 创建并显示客户菜单界面
            customerMenuFrame.setVisible(true);
        });
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String itemId = itemField.getText().trim();
                int quantity;
                try {
                    quantity = Integer.parseInt(quantityField.getText().trim());
                    if (quantity <= 0) {
                        JOptionPane.showMessageDialog(null, "数量必须大于0");
                        return;
                    }
                    if (inventory.containsKey(itemId)) {
                        int available = inventory.get(itemId);
                        if (quantity > available) {
                            JOptionPane.showMessageDialog(null, "库存不足");
                            return;
                        }
                        cart.put(itemId, cart.getOrDefault(itemId, 0) + quantity);
                        inventory.put(itemId, available - quantity);
                        updateCartDisplay();
                        updateInventoryDisplay();
                    } else {
                        JOptionPane.showMessageDialog(null, "无效的商品编号");
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(null, "请输入有效的数量");
                }
            }
        });

        removeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String itemId = itemField.getText().trim();
                if (cart.containsKey(itemId)) {
                    int confirm = JOptionPane.showConfirmDialog(null, "确定要移除该商品吗?", "确认", JOptionPane.YES_NO_OPTION);
                    if (confirm == JOptionPane.YES_OPTION) {
                        cart.remove(itemId);
                        updateCartDisplay();
                        updateInventoryDisplay();
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "购物车中没有该商品");
                }
            }
        });

        modifyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String itemId = itemField.getText().trim();
                int quantity;
                try {
                    quantity = Integer.parseInt(quantityField.getText().trim());
                    if (quantity < 0) {
                        // 如果数量小于 0，表示用户希望从购物车中移除该商品
                        cart.remove(itemId);
                        // 将库存恢复为原来的数量
                        if (inventory.containsKey(itemId)) {
                            inventory.put(itemId, inventory.get(itemId) + quantity);
                        }
                    } else if (quantity == 0) {
                        // 如果数量为 0，表示用户希望将商品从购物车中移除
                        cart.remove(itemId);
                    } else if (cart.containsKey(itemId)) {
                        // 只有当商品在购物车中时，进行修改
                        int currentQuantity = cart.get(itemId);
                        int available = inventory.getOrDefault(itemId, 0);
                        int newAvailable = available + currentQuantity - quantity;

                        if (newAvailable < 0) {
                            JOptionPane.showMessageDialog(null, "库存不足");
                            return;
                        }

                        cart.put(itemId, quantity);
                        inventory.put(itemId, newAvailable);
                    } else {
                        // 商品不在购物车中
                        JOptionPane.showMessageDialog(null, "购物车中没有该商品");
                    }
                    updateCartDisplay();
                    updateInventoryDisplay();
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(null, "请输入有效的数量");
                }
            }
        });


        checkoutButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String[] options = {"支付宝", "微信", "银行卡"};
                int choice = JOptionPane.showOptionDialog(null, "选择支付方式", "结账", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
                if (choice >= 0) {
                    // 模拟支付
                    JOptionPane.showMessageDialog(null, "支付成功: " + options[choice]);
                    StringBuilder sb = new StringBuilder();
                    for (Map.Entry<String, Integer> entry : cart.entrySet()) {
                        sb.append("商品编号: ").append(entry.getKey()).append(", 数量: ").append(entry.getValue()).append("\n");
                        inventory.put(entry.getKey(), inventory.getOrDefault(entry.getKey(), 0) + entry.getValue());
                    }
                    cart.clear();
                    updateCartDisplay();
                    updateInventoryDisplay();
                    String historyEntry = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + sb.toString();
                    purchaseHistory.add(historyEntry);
                }
            }
        });

        historyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                StringBuilder sb = new StringBuilder();
                for (String entry : purchaseHistory) {
                    sb.append(entry).append("\n");
                }
                historyArea.setText(sb.toString());
            }
        });
        updateInventoryDisplay();
        updateCartDisplay();
        updateHistoryDisplay();
    }

    private void updateInventoryDisplay() {
        StringBuilder inventoryText = new StringBuilder("商品库存:\n");
        for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
            inventoryText.append("商品编号: ").append(entry.getKey())
                    .append(", 库存: ").append(entry.getValue()).append("\n");
        }
        inventoryArea.setText(inventoryText.toString());
    }

    private void updateCartDisplay() {
        StringBuilder cartText = new StringBuilder("购物车内容:\n");
        for (Map.Entry<String, Integer> entry : cart.entrySet()) {
            cartText.append("商品编号: ").append(entry.getKey())
                    .append(", 数量: ").append(entry.getValue()).append("\n");
        }
        cartArea.setText(cartText.toString());
    }

    private void updateHistoryDisplay() {
        StringBuilder historyText = new StringBuilder("购物历史:\n");
        for (String record : purchaseHistory) {
            historyText.append(record).append("\n");
        }
        historyArea.setText(historyText.toString());
    }
}
